<?php

require('globals.php');

// Global JS functions and scripts.
// For some reason, moving all of these into a general `globals` file frotzes.  No idea why.

?>

var table_array = new Array(new Array(),new Array(),new Array(),new Array(),new Array());
var query_array = new Array();
var selected = 0;

// for the mouse context menu on Layout Report
var _replaceContext = false;        // replace the system context menu?
var _mouseOverContext = false;      // is the mouse over the context menu?
var _noContext = false;             // disable the context menu?
var _divContext = $('divContext');  // makes my life easier

// onLoad function that calls, well, functions
// trying to nest functions in onLoad() doesn't work
function SetItOff() {
	populateTableArray();
	defaultValuation();
	//original_form = $('submit').serialize();
}

function populateTableArray() {

	// This function creates a multi-tier array of arrays of table info
	// for each particular level of table sizes
	// It does not verify that tables are actually available
	//
	// This could probably be restructured to only do the for(keyVar in
	// row_headers) once as one giant loop to increase effeciency
	// (much less resetting of i and j--instead of filling each
	// individual array at once, fill each row's one-by-one)
	// the problem there is that the five arrays are greatly
	// dissimiliar, which makes the idea of doing all-at-once
	// much more difficult
	//
	// table_array[0][] is Halves
	// table_array[1][] is Fulls
	// table_array[2][] is Doubles
	// table_array[3][] is Triples
	// table_array[4][] is Islands
	//
	// Islands have been removed for 2010
	// Islands are in but manual for 2011
	// Layout is -completely- changed in 2012

	var row_headers = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O');
	var x=0, i=0, j=1, limiter=40;
	var marker = 0;

	// half tables
	//for (keyVar in row_headers) {		// Prototype.js mucks with for-in loops in a completely moronic way
	row_headers.each(function(keyVar) {
		if (row_headers.indexOf(keyVar) >= 0 && row_headers.indexOf(keyVar) < 3)
			shift = 0;
		if (row_headers.indexOf(keyVar) > 4 && row_headers.indexOf(keyVar) < 9)
			shift = (30 * (row_headers.indexOf(keyVar)-4));
		else
			shift = shift;
		for (x=0; i < ((limiter*j)-shift); x++) {
			if (x+1 <= 9 && (row_headers.indexOf(keyVar) <= 4 || row_headers.indexOf(keyVar) >= 9)) {
				table_array[0][i] = row_headers[row_headers.indexOf(keyVar)] + '0' + ((keyVar > 'E' && keyVar < 'K') ? (x+16) : (x+1)) + 'A';
				table_array[0][++i] = row_headers[row_headers.indexOf(keyVar)] + '0' + ((keyVar > 'E' && keyVar < 'K') ? (x+16) : (x+1)) + 'B';
			} else {
				table_array[0][i] = row_headers[row_headers.indexOf(keyVar)] +  ((keyVar > 'E' && keyVar < 'K') ? (x+16) : (x+1)) + 'A';
				table_array[0][++i] = row_headers[row_headers.indexOf(keyVar)] + ((keyVar > 'E' && keyVar < 'K') ? (x+16) : (x+1)) + 'B';
			}
			i++;
		}
		j++;
	})

	i=0;
	j=1;
	limiter = 20;

	// same process for Fulls
	//for (keyVar in row_headers) {
	row_headers.each(function(keyVar) {
		index = row_headers.indexOf(keyVar);
		//document.write(index + "<BR>");
		if (index >= 0 && index < 3)
			shift = 0;
		if (index > 4 && index < 9)
			shift = (15 * (index - 4));
		for (x=0; i < ((limiter)*j)-shift; x++) {
			if (index > 4 && index < 9)
				marker = x + 16;
			else
				marker = x + 1;
			table_array[1][i] = row_headers[index] + (marker > 9 ? marker : '0' + marker);
			i++;
		}
		j++;
	})

	i=0;
	j=1;
	limiter = 16;

	//Doubles

	for (keyVar in row_headers) {
		if (keyVar >= 0 && keyVar < 3)
			shift = 0;
		if (keyVar > 4 && keyVar < 9)
			shift = (12 * (keyVar - 4));
		for (x=0; i < ((limiter*j)-shift); x++) {
			if ((x + 1 != 5) && (x + 1 != 11) && (x + 1 != 15)) {
				if (keyVar > 4 && keyVar < 9)
					marker = x + 16
				else
					marker = x + 1
				table_array[2][i] = row_headers[keyVar] + (marker > 9 ? marker : '0' + marker) + "/"
										+ row_headers[keyVar] + (marker + 1 > 9 ? marker + 1 : '0' + (marker + 1));
			i++;
			}
		}
		j++;
	}

	i=0;
	j=1;
	limiter = 12;

	// Triples
	for (keyVar in row_headers) {
		if (keyVar >= 0 && keyVar < 3)
			shift = 0;
		if (keyVar > 4 && keyVar < 9)
			shift = (9 * (keyVar - 4));
		for (x=0; i < ((limiter*j)-shift); x++) {
			if ((x + 1 != 5) && (x + 2 != 5)
				 && (x + 1 != 11) && (x + 2 != 11)
				 && (x + 1 != 15) && (x + 2 != 15)) {
				if (keyVar > 4 && keyVar < 9)
					marker = x + 16;
				else
					marker = x + 1;
				table_array[3][i] = row_headers[keyVar] + (marker > 9 ? marker : '0' + marker) + "/" +
									row_headers[keyVar] + (marker + 1 > 9 ? marker + 1 : '0' + (marker + 1)) + "/" +
									row_headers[keyVar] + (marker + 2 > 9 ? marker + 2 : '0' + (marker + 2));
			i++;
			}
		}
		j++;
	}

	// Islands
	table_array[4][0] = 'I01'
	table_array[4][1] = 'I02'
	table_array[4][2] = 'I03'
	table_array[4][3] = 'I04'
	table_array[4][4] = 'I05'
	table_array[4][5] = 'I06'

	// additional tables that are complex to introduce automatically
	table_array[0].splice(table_array[0].length+1, 0,
				'B00CA', 'B00CB', 'B21CA', 'B21CB', 'D00EA', 'D00EB', 'D21EA', 'D21EB',
				'F16GA', 'F16GB', 'F21GA', 'F21GB', 'H21JA', 'H21JB', 'H21JA', 'H21JB',
				'K00LA', 'K00LB', 'K21LA', 'K21LB', 'M00NA', 'M00NB', 'M21NA', 'M21NB'
	);

	table_array[1].splice(table_array[1].length+1, 0,
				'B00C', 'B21C', 'D00E', 'D21E',
				'F15G', 'F21G', 'H15J', 'H21J',
				'K00L', 'K21L', 'M00N', 'M21N'
	);
}

function populateMenus(selectCtrl, tableSizeIndex, itemArray, defaultItem, power, wall) {
	var i, j = 0;
	var prompt;

	<?php

		$query = "SELECT * FROM " . $tables_table . " WHERE left(row_number,1) != 'I' ORDER BY length(row_number), row_number";

		if (!($link = mysql_connect($host, $user, $password)))
			die('Could not connect: ' . mysql_error());

		if (!(mysql_select_db($database)))
			die('Could not select db ' . $database . ': ' . mysql_error());

		$result = mysql_query($query, $link);

		$kicker = 0;

		while($row = mysql_fetch_row($result)) {
					$array_init_string .= $row[1] . ",";
					$array_init_string .= $row[2] . ",";
		}

		$array_init_string = substr($array_init_string, 0, -1);

		mysql_close($link);
	?>

	var tableinitarray = Array(<?php echo($array_init_string); ?>);

	RemoveIrrelevantElements(itemArray, power, wall);
	IsThisSeatTaken(tableinitarray, itemArray, tableSizeIndex, defaultItem);
	//patchedArray = itemArray;	// for testing purposes

	selectCtrl.options.length = 0;

	if (patchedArray != null) {
		// add new items
		for (i = 0; i < patchedArray.length; i++) {
			selectCtrl.options[j] = new Option(patchedArray[i]);
			if (patchedArray[i] != null)
				selectCtrl.options[j].value = patchedArray[i];
			//window.alert(patchedArray[i] + "<BR>");
			j++;
		}
		// select first item (prompt) for sub list
		selectCtrl.options[selected].selected = true;
   	}
}

function IsThisSeatTaken(tablestatearray, tablelistarray, size, defaultItem) {

	// generates the "culled" table listings to avoid dupe assignments

	var j = 0, i = 0; k = 0;
	var retarded;

	patchedArray = new Array();

	var assignedTable = defaultItem;

	switch (size) {
		case (0):
			for (i = 0; i < tablelistarray.length; i++) {
				if (tablestatearray[j] == '000'  || tablelistarray[i] == assignedTable)
					patchedArray[k++] = tablelistarray[i];
				j++;
				if (tablelistarray[i] == assignedTable)
					selected = k - 1;
			}
			break
		case (1):
			for (i = 0; i < tablelistarray.length; i++) {
				if ((tablestatearray[j] == '000' && tablestatearray[j+1] == '000') || tablelistarray[i] == assignedTable)
					patchedArray[k++] = tablelistarray[i];
				j += 2;
				if (tablelistarray[i] == assignedTable)
					selected = k - 1;
			}
			break
		case (2):
			for (i = 0; i < tablelistarray.length; i++) {
				if (i == tablelistarray.length - 1)			// blowing past the end of the array
					retarded = "9999999";					// makes JS puke up errors
				else
					retarded = tablelistarray[i];
				if ((tablestatearray[j] == '000' && tablestatearray[j+1] == '000'
					&& tablestatearray[j+2] == '000' && tablestatearray[j+3] == '000')
					|| tablelistarray[i] == assignedTable)
						patchedArray[k++] = tablelistarray[i];
				if (tablelistarray[i].substring(6) == 5  ||
				    tablelistarray[i].substring(5) == 11 ||
				    tablelistarray[i].substring(5) == 15 ||
				    tablelistarray[i].substring(5) == 20)
					j += 4;
				else j += 2;
				if (tablelistarray[i] == assignedTable)
					selected = k - 1;
			}
			break;
		case (3):
			for (i = 0; i < tablelistarray.length; i++) {
				if (i == tablelistarray.length - 1)		// blowing past the end of the array
					retarded = "9999999";				// makes JS puke up errors
				else
					retarded = tablelistarray[i];
				if ((tablestatearray[j] == '000' && tablestatearray[j+1] == '000'
					&& tablestatearray[j+2] == '000' && tablestatearray[j+3] == '000'
					&& tablestatearray[j+4] == '000' && tablestatearray[j+5] == '000')
					|| tablelistarray[i] == assignedTable)
					patchedArray[k++] = tablelistarray[i];
				if (tablelistarray[i].substring(10) == 5 ||
				    tablelistarray[i].substring(9) == 11 ||
				    tablelistarray[i].substring(9) == 15 ||
				    tablelistarray[i].substring(9) == 20)
				    j += 6;
				else j += 2;
				if (tablelistarray[i] == assignedTable)
					selected = k - 1;
			}
			break
		case (4):			// kludge T_T - this (still as of 2013) does not presently cull
			patchedArray[0] = ('I01');
			patchedArray[1] = ('I02');
			patchedArray[2] = ('I03');
			patchedArray[3] = ('I04');
			patchedArray[4] = ('I05');
			patchedArray[5] = ('I06');
			break;
		default:
			break;
	}
}

function InitContext()
{
    _divContext.onmouseover = function() { _mouseOverContext = true; };
    _divContext.onmouseout = function() { _mouseOverContext = false; };

    $('aDisable').onclick = DisableContext;
    $('aEnable').onclick = EnableContext;

    document.body.onmousedown = ContextMouseDown;
    document.body.oncontextmenu = ContextShow;
}

// call from the onMouseDown event, passing the event if standards compliant
function ContextMouseDown(event)
{
    if (_noContext || _mouseOverContext)
        return;

    // IE is evil and doesn`t pass the event object
    if (event == null)
        event = window.event;

    // we assume we have a standards compliant browser, but check if we have IE
    var target = event.target != null ? event.target : event.srcElement;

    // only show the context menu if the right mouse button is pressed
    //   and a hyperlink has been clicked (the code can be made more selective)
    if (event.button == 2 && target.tagName.toLowerCase() == 'a')
        _replaceContext = true;
    else if (!_mouseOverContext)
        _divContext.style.display = 'none';
}

function CloseContext()
{
    _mouseOverContext = false;
    _divContext.style.display = 'none';
}

// call from the onContextMenu event, passing the event
// if this function returns false, the browser`s context menu will not show up
function ContextShow(event)
{
    if (_noContext || _mouseOverContext)
        return;

    // IE is evil and doesn`t pass the event object
    if (event == null)
        event = window.event;

    // we assume we have a standards compliant browser, but check if we have IE
    var target = event.target != null ? event.target : event.srcElement;

    if (_replaceContext)
    {
        $('aContextNav').href = target.href;
        $('aAddWebmark').href = 'http://luke.breuer.com/webmark/?addurl=' +
            encodeURIComponent(target.href) + '&title=' +
            encodeURIComponent(target.innerHTML);

        // document.body.scrollTop does not work in IE
        var scrollTop = document.body.scrollTop ? document.body.scrollTop :
            document.documentElement.scrollTop;
        var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
            document.documentElement.scrollLeft;

        // hide the menu first to avoid an "up-then-over" visual effect
        _divContext.style.display = 'none';
        _divContext.style.left = event.clientX + scrollLeft + 'px';
        _divContext.style.top = event.clientY + scrollTop + 'px';
        _divContext.style.display = 'block';

        _replaceContext = false;

        return false;
    }
}

function DisableContext() {
    _noContext = true;
    CloseContext();
    $('aEnable').style.display = '';

    return false;
}

function EnableContext() {
    _noContext = false;
    _mouseOverContext = false; // this gets left enabled when "disable menus" is chosen
    $('aEnable').style.display = 'none';

    return false;
}

// function attempts to remove tables that are not valid for a given applicant
// from the list to avoid bad assignments
function RemoveIrrelevantElements(itemArray, power, wall) {
	var i = 0;

	if (wall) {
		while (itemArray[i]) {
			if(itemArray[i].substr(0,1) != 'A' && itemArray[i].substr(0,1) != 'O') {
				itemArray.splice(i,1);
			}
			else
				i++;
		}
	} else {
		while (itemArray[i]) {
			if(itemArray[i].substr(0,1) == 'A' || itemArray[i].substr(0,1) == 'O') {
				itemArray.splice(i,1);
			}
			else
				i++;
		}
	}

	i = 0;
	var number;
	var row;

	if (!power) {
		while (itemArray[i]) {
			number = itemArray[i].substr(1,2);
			row = itemArray[i].substr(0,1);
			if ((number >= 6 && number <= 15 &&
					(row == 'A' || row == 'C' || row == 'D' || row == 'K' || row == 'N'))
				|| (number >= 6 && number <= 11 && row == 'O')
				|| row == 'J')
					itemArray.splice(i,1);
			else
				i++;
		}
	} else {
		while (itemArray[i]) {
			number = itemArray[i].substr(1,2);
			row = itemArray[i].substr(0,1);
			if (((row == 'B' || (row >= 'E' && row <= 'I') || row == 'K' || row == 'M'))
					|| (number < 6 || number > 15)
					|| (row == 'O' && number > 11))
					itemArray.splice(i,1);
			else
				i++;
		}
	}
}